﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using Model;
using System.Data.Entity;

namespace BLL
{
    public class AppBLL
    {
        AppDbContext context = new AppDbContext(System.Configuration.ConfigurationManager.ConnectionStrings["SysDbContext"].ConnectionString);

        public AppDbContext DbContext { get { return context; } }

        /// <summary>
        /// Dlete NodeRelationship by node'ID
        /// </summary>
        /// <param name="id"></param>
        public void DeleteRelationshipByNodeID(Guid id)
        {
            context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "delete NodeRelationship where NodeID='" + id.ToString() + "'");
        }

        public ProjectView GetProjectViewByID(Guid id)
        {
            ProjectView view = null;
            var project = DbContext.Projects.FirstOrDefault(x => x.ID == id);
            if (project == null)
            {
                return null;
            }
            //DbContext.ProjectNodes.Load();
            //DbContext.ProjectAreas.Load();
            view = new ProjectView();
            view.Project = project;
            view.Areas = DbContext.ProjectAreas.Where(x => x.ProjectID == id).ToList();
            view.Nodes = DbContext.ProjectNodes.Where(x => x.ProjectID == id).ToList();
            var nodes = from x in view.Nodes select x.ID;
            view.Relationships = DbContext.NodeRelationships.Where(x => nodes.Contains(x.NodeID)).ToList();

            return view;
        }

        public void RefreshData(ProjectView project)
        {
            var nodes = project.Nodes.OrderBy(x => x.Order).ToList();
            nodes.ForEach(x =>
            {

            });
        }

        public void DeletePoint(Guid id)
        {
            var contacts = DbContext.NodePointContactses.Where(x => x.NodePointID == id);
            DbContext.NodePointContactses.RemoveRange(contacts);
            var pnpRemoved = new ProjectNodePoint { ID = id };
            DbContext.ProjectNodePoints.Attach(pnpRemoved);
            DbContext.Entry(pnpRemoved).State = EntityState.Deleted;
        }

        public void Delete(Project project)
        {
            var nodes = DbContext.ProjectNodes.Where(w => w.ProjectID == project.ID).ToList();
            nodes.ForEach(x =>
            {
                x.ProjectID = null;
            });
            DbContext.Projects.Attach(project);
            DbContext.Projects.Remove(project);
        }
    }
}
